#include "StoreInstruction.h"
#include "VoidType.h"

StoreInstruction::StoreInstruction(Function * func, Value * ptr, Value * value)
    : Instruction(func, IRInstOperator::IRINST_OP_STORE, VoidType::getType()), value_(value), ptr_(ptr)
{
    addOperand(ptr_);
    addOperand(value_);
}

void StoreInstruction::toString(std::string & str)
{
    std::string valType = value_ ? value_->getType()->toString() : "null";
    std::string valName = value_ ? value_->getIRName() : "null";
    std::string ptrType = ptr_ ? ptr_->getType()->toString() : "null";
    std::string ptrName = ptr_ ? ptr_->getIRName() : "null";

    // 检查源操作数是否为LocalVariable或GlobalVariable
    if (dynamic_cast<LocalVariable*>(value_) || dynamic_cast<GlobalVariable*>(value_)) {
        // 生成临时变量
        RegVariable* tempVar = func->newTempVariable(value_->getType());
        std::string tempName = tempVar->getIRName();
        str = tempName + " = load " + valType + ", " + valType + "* " + valName + "\n\t";
        str += "store " + valType + " " + tempName + ", " + ptrType + " " + ptrName;
    } else {
        str = "store " + valType + " " + valName + ", " + ptrType + " " + ptrName;
    }
}